<template>
  <div class="pannel-account">
    <el-form :model="account" :rules="accountRules" :label-width="150" size="large" status-icon ref="formRef">
      <el-form-item label="单位全称" prop="name">
        <el-input v-model.trim="account.name" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input />
      </el-form-item>
      <el-form-item label="验证码">
        <div class="verify-code">
          <el-input />
          <el-button class="get-btn" type="primary">获取验证码</el-button>
        </div>
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model.trim="account.password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="password">
        <el-input v-model.trim="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import useLoginStore from '@/store/login/login'
import type { FormRules } from 'element-plus'
import { ElForm, ElMessage } from 'element-plus'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'

const loginStore = useLoginStore()
const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'

const account = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})
const formRef = ref<InstanceType<typeof ElForm>>()

const accountRules: FormRules = {
  name: [
    { required: true, message: '必须输入帐号信息~', trigger: 'blur' },
    {
      pattern: /[a-z0-9]{6,20}/,
      message: '必须是6~20位数字或字母组成~',
      trigger: 'change'
    }
  ],
  password: [
    { required: true, message: '必须输入密码信息~', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{3,}$/,
      message: '必须是3位以上的数字或字母组成~',
      trigger: 'change'
    }
  ]
}

const loginAction = (isRemPwd: boolean) => {
  formRef.value?.validate((valid) => {
    if (valid) {
      loginStore.loginAccountAction(account).then(() => {
        if (isRemPwd) {
          localCache.setCache(CACHE_NAME, account.name)
          localCache.setCache(CACHE_PASSWORD, account.password)
        } else {
          localCache.removeCache(CACHE_NAME)
          localCache.removeCache(CACHE_PASSWORD)
        }
      })
      // ElMessage({
      //   type: 'success',
      //   message: '登录成功~'
      // })
    } else {
      ElMessage.error('Oops, 请您输入正确的格式后再操作~~.')
    }
  })
}

defineExpose({
  loginAction
})
</script>

<style lang="less" scoped>
.pannel-account {
  color: red;
}

.test-account {
  font-size: 12px;
  color: #000;
}

.verify-code {
  display: flex;
  width: 100%;

  .get-btn {
    margin-left: 8px;
  }
}
</style>
